""" removeall.py:

   Clean up a directory tree from root.
   The directory need not be empty.
   The starting directory is not deleted.
   Written by: Anand B Pillai <abpillai@lycos.com> """

import sys, os, stat

ERROR_STR= """Error removing %(path)s, %(error)s """

def rmgeneric(path, __func__):
    try:
        __func__(path)
        print 'Removed ', path
    except OSError, e1:
        print "Failed First attempt ", e1.errno, " ", e1.strerror
        # set the file to writable and retry. This is Windows problem
        try:            
            os.chmod (path, stat.S_IWRITE)
            __func__(path)
        except OSError, e2:
            print "Failed Second attempt", e2.errno, " ", e2.strerror            
                
            
def removeall(path):

    if not os.path.isdir(path):
        return
    
    files=os.listdir(path)

    for x in files:
        fullpath=os.path.join(path, x)
        if os.path.isfile(fullpath):
            f = os.remove
            rmgeneric(fullpath, f)
        elif os.path.isdir(fullpath):
            removeall(fullpath)
            f = os.rmdir
            rmgeneric(fullpath, f)
    
    f = os.rmdir
    rmgeneric(path, f)
    

